package com.dangdang.service.impl;

import com.dangdang.dao.UserDao;
import com.dangdang.entity.User;
import com.dangdang.service.UserService;
import com.dangdang.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

public class UserServiceImpl implements UserService {
    @Override
    public User login(String email, String pwd) {
        User user = null;
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil.getSqlSession();
            UserDao dao = sqlSession.getMapper(UserDao.class);
            user = dao.selectByEmailAndPwd(email, pwd);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return user;
    }
    public Boolean regist(User u){
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil.getSqlSession();
            UserDao dao = sqlSession.getMapper(UserDao.class);
            User user = dao.selectByEmail(u.getEmail());
            if(user!=null){
                return false;
            }
            dao.insert(u);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return true;
    }
    public User selectByEmail(String email){
        SqlSession sqlSession = null;
        User user = null;
        try {
            sqlSession = MyBatisUtil.getSqlSession();
            UserDao dao = sqlSession.getMapper(UserDao.class);
            user = dao.selectByEmail(email);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return user;
    }
}
